package com.aaa.sys.controller;


import com.aaa.vo.R;
import com.aaa.sys.entity.Menu;
import com.aaa.sys.service.MenuService;
import com.aaa.sys.vo.MenuSeacher;
import com.aaa.sys.vo.MenuTree;
import com.aaa.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author ykq
 * @since 2020-11-25
 */
@RestController
@RequestMapping("/system/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;
    @GetMapping("queryMenuTreeByUserId")
    public R queryMenuTreeByUserId(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId=JwtUtils.getMemberIdByJwtToken(token);
        List<MenuTree> menuTree = menuService.findMenuTreeByUserId(userId);
        return R.ok().message("菜单加载成功").data("menuTree",menuTree);
    }

    @PostMapping("queryMenuTreeByCon")
    public R queryMenuTreeByCon(@RequestBody MenuSeacher menu){
        List<Menu> menuTree = menuService.queryMenuTreeByCon(menu.getFullName());

        return R.ok().message("菜单加载成功").data("allMenuTree",menuTree);
    }

    //分配权限
    @PostMapping("fenPermission/{roleId}")
    public R queryMenuTreeByCon(@PathVariable Long roleId){
        List<Menu> menuTree = menuService.queryMenuTreeByCon(null);
        List<Integer> expandKey=menuService.queryExpandMenuKey(roleId);
        return R.ok().message("菜单加载成功").data("allMenuTree",menuTree).data("checkedKey",expandKey);
    }
    @DeleteMapping("deleteMenu/{menuId}")
    public R deleteMenu(@PathVariable("menuId")Long menuId){
        try {
            boolean b = this.menuService.removeById(menuId);
            return R.ok().message("删除菜单成功");
        }catch (Exception e){
            return R.error().message("删除菜单失败");
        }
    }
    @PostMapping("addMenu")
    public R addDept(@RequestBody Menu menu){
        try {
            boolean row = menuService.save(menu);
            return R.ok().message("菜单加载成功");
        }catch (Exception e){
            return R.error().message("菜单添加失败");
        }
    }

    @GetMapping("getMenuById/{menuId}")
    public R getMenuById(@PathVariable("menuId")Long menuId){
        try {
            Menu menu = menuService.getById(menuId);
            return R.ok().data("menu",menu);
        }catch (Exception e){
            return R.error().message("菜单加载失败");
        }
    }

    @PostMapping("editMenu")
    public R editMenu(@RequestBody Menu menu){
        try {
            boolean row = menuService.updateById(menu);
            return R.ok().message("菜单修改成功");
        }catch (Exception e){
            return R.error().message("菜单修改失败");
        }
    }
}

